<template>
  <div class="BasciTools">
    <div id="BasciTools-map" style="width:100%;height:658px"></div>
    <div id="BasciTools-mapDiv" class="ol-popup" style="position: absolute;top: 33px;left: -16px;">
      <!-- 显示控件 -->
      <div id="BasciTools-setDivPosition" class="init-setDivPosition">
        <!-- 返回主界面 -->
        <p @click="mapDrawTaskPolygon" :class="{ 'init-setDivPosition-selected': zoomDefaultPositionBool == false }">
          <img src="@/assets/map/image/icon-多边形.png" title="多边形绘制"><br /><span style="border:0;">多边形</span>
        </p>
      </div>
    </div>
  </div>
</template>
<script>
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import { Vector as VectorSource } from 'ol/source'
import { Draw } from 'ol/interaction';
import { Fill, Stroke, Style } from 'ol/style';
import { getProjection, getTiandituVecMap, getTiandituVecText } from "@/map/projMap.js";
export default ({
  name: 'BasicToolMap',
  emits: ['getPolygonGeom'],
  props: {
    dialogVisible: {//灾区范围图例列表
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      str: 'BasciTools',
      map: null,
      center: [105, 34],
      zoom: 4,
      layer1: null,
      layer2: null,
      source: null,// 矢量绘制图层
      zoomDefaultPositionBool: true,
      draw: null,
    }
  },
  watch: {
    dialogVisible: {//灾区范围图例列表
      handler: function (newVal, oldVal) {
        if (newVal) {
          if (this.source != null) {
            this.source.clear();
          }
        }
      },
      immediate: true
    },
  },
  mounted() {
    let that = this
    this.$nextTick(function () {
      setTimeout(() => {
        // 初始化地图
        that.initMap()
      }, 200)
    })
  },
  methods: {
    initMap() {
      let that = this
      let targetMap = document.getElementById(this.str + '-map')
      // 清空targetMap
      targetMap.innerHTML = ''
      // 获取地图div的高度
      this.autodivheight()
      // 浏览器窗口发生变化时同时变化DIV高度
      window.onresize = this.autodivheight()
      if (this.map) { //避免地图重复加载
        return
      }
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution: true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
        })
      });
      this.layer1 = getTiandituVecMap()
      this.map.addLayer(this.layer1)
      this.layer2 = getTiandituVecText()
      this.map.addLayer(this.layer2)
      this.layer1.setZIndex(0)
      this.layer2.setZIndex(0)
      //矢量绘制图层
      this.source = new VectorSource({
        wrapX: false
      });
      let vectorLayer = new VectorLayer({
        source: that.source,
        projection: 'EPSG:4490'
      });
      this.map.addLayer(vectorLayer);
      vectorLayer.setZIndex(2);
    },
    //多边形绘制创建任务工作区域
    mapDrawTaskPolygon() {
      let that = this
      that.source.clear();
      if (this.zoomDefaultPositionBool) {
        this.zoomDefaultPositionBool = false
        this.draw = new Draw({
          source: this.source,
          type: 'Polygon'
        });
        this.map.addInteraction(this.draw);
        this.draw.on('drawend', function (e) {
          let geometry = e.feature.getGeometry().getCoordinates()[0];
          let polygonWkt = "POLYGON((";
          for (let i = 0; i < geometry.length; i++) {
            if (i > 0) {
              polygonWkt += ",";
            }
            let lonlat = geometry[i];
            polygonWkt += lonlat[0] + " " + lonlat[1];
          }
          polygonWkt += "))";
          that.map.removeInteraction(that.draw);
          that.draw = null;
          that.zoomDefaultPositionBool = true
          that.$confirm('是否保存此范围?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.$message({
              type: 'success',
              message: '保存成功!'
            });
            that.$emit("getPolygonGeom", polygonWkt);
          }).catch(() => {
            that.source.clear();
            that.$message({
              type: 'info',
              message: '已取消保存'
            });
          });
        });
      } else {
        //停止绘制
        this.map.removeInteraction(this.draw);
        this.draw = null;
        this.zoomDefaultPositionBool = true
      }
    },
    getPolyonStyle(color) {//多边形样式
      let style = new Style({
        fill: new Fill({//填充样式
          color: "rgba(0,0,0,0)"
        }),
        stroke: new Stroke({//描绘
          width: 2,//宽
          color: color
        }),
        zIndex: 100
      });
      return style;
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if (mapHeight < 480) {
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str + "-map").style.height = mapHeight + "px";
      console.log("窗口高度：" + winHeight + "地图高度：" + mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if (this.map) {
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
  }
})
</script>
<style lang="scss" scoped>
#BasciTools{
  position: relative;
  &-mapDiv{
    left: 0!important;
  }
  &-setDivPosition{
    top: 36px;
  }
}
</style>